<template>
  <div class="auth-card">
    <el-form
      class="hospital-auth-form"
      :model="hospitalAuthForm"
      ref="hospitalAuthForm"
      :rules="hospitalAuthFormRules"
    >
      <h3>授权有效期</h3>
      <el-form-item prop="dateArr">
        <el-date-picker
          v-model="hospitalAuthForm.dateArr"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <h3>上传合同书</h3>
      <el-form-item prop="contractUrl">
        <el-upload
          class="contract-uploader"
          action="string"
          :show-file-list="false"
          :disabled="load.isImgLoading"
          :before-upload="beforeUpload"
          :accept="load.uploadAccept"
          :http-request="handleUpload"
        >
          <div class="img-box">
            <div class="img-ready" v-if="hospitalAuthForm.contractUrl">
              <i style="font-size:38px;" class="iconfont iconpdf pdf-logo" />
              <p style="line-height:16px;">修改</p>
            </div>
            <div class="no-img" v-else>+</div>
          </div>
        </el-upload>
      </el-form-item>
      <h3>合同编号</h3>
      <el-form-item prop="contractCode">
        <el-input v-model="hospitalAuthForm.contractCode"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          style="width:100%; height:50px;"
          type="primary"
          @click="submitResult"
          >提 交</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {fileUpload} from '@const/api_aggregation'
import {authSupplierHospital} from '@const/api_authCenter.js'
import {formatDate} from '@const/filter.js'
export default {
  name: 'authCard',
  data() {
    return {
      hospitalAuthForm: {
        dateArr: [],
        contractUrl: '',
        contractCode: '',
        contractName: ''
      },
      load: {
        uploadAccept: '.pdf',
        uploadApi: fileUpload,
        isImgLoading: false
      },
      hospitalAuthFormRules: {
        dateArr: [
          {required: true, message: '授权有效期必填', trigger: 'change'}
        ],
        contractUrl: [
          {required: true, message: '请上传合同书', trigger: 'change'}
        ],
        contractCode: [
          {required: true, message: '请输入合同编号', trigger: 'change'}
        ]
      }
    }
  },
  methods: {
    submitResult() {
      this.$refs['hospitalAuthForm'].validate(valid => {
        if (valid) {
          this.$axios({
            method: 'post',
            url: authSupplierHospital,
            params: {flag: 'link'},
            data: {
              validityFrom:
                formatDate(this.hospitalAuthForm.dateArr[0], 'YYYY-MM-DD') ||
                '',
              validityTo:
                formatDate(this.hospitalAuthForm.dateArr[1], 'YYYY-MM-DD') ||
                '',
              contractUrl: this.hospitalAuthForm.contractUrl,
              contractName: this.hospitalAuthForm.contractName,
              contractCode: this.hospitalAuthForm.contractCode,
              hospitalContactId: this.$route.query.id
            }
          }).then(res => {
            if (res.data.code === '0') {
              // TODO 跳转到指定页面
              this.$router.replace(this.$PATH_CONST.main_page)
            } else {
              // TODO 失败提示
              this.$confirm(
                '未知错误，确认后直接进入M平台，或取消后重新登录',
                '提示',
                {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }
              )
                .then(() => {
                  this.$router.replace(this.$PATH_CONST.main_page)
                })
                .catch(() => {
                  this.$router.push(this.$PATH_CONST.login_page)
                })
            }
          })
        }
      })
    },
    beforeUpload(file) {
      let FileExt = file.name.replace(/.+\./, '') // 名字后缀
      const isLt1M = file.size / 1024 / 1024 < 1 // 文件大小
      const format = this.load.uploadAccept.includes(FileExt.toLowerCase())
      if (!format) {
        this.$message.error(`上传文件只支持${this.load.uploadAccept}类型!`)
      } else if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 1MB!')
      }
      return isLt1M && format
    },
    handleUpload(data) {
      this.load.isImgLoading = true
      this.hospitalAuthForm.contractName = data.file.name.split('.')[0]
      // 发起请求
      let fd = new FormData()
      fd.append('file', data.file)
      this.$axios({
        method: 'post',
        url: this.load.uploadApi,
        headers: {'Content-Type': 'multipart/form-data'},
        data: fd
      })
        .then(res => {
          const {code, payload} = res.data
          if (code === '0') {
            this.$message({type: 'success', message: '上传成功'})
            this.hospitalAuthForm.contractUrl = payload
          } else {
            this.$message({type: 'error', message: res.data.msg})
          }
        })
        .catch(() => {
          this.$message({type: 'error', message: '文件上传失败，请重新选择'})
        })
        .finally(() => {
          this.load.isImgLoading = false
        })
    }
  }
}
</script>
<style lang="less">
.auth-card {
  box-sizing: border-box;
  width: 420px;
  height: 449px;
  padding: 40px 32px 70px;
  background-color: #fff;
  h3 {
    color: #26344c;
    font-size: 14px;
    margin: 10px 0;
  }
  .img-box {
    width: 60px;
    height: 60px;
    color: #1164bd;
    .no-img,
    .img-ready {
      width: 100%;
      height: 100%;
    }
    .no-img {
      text-align: center;
      line-height: 50px;
      font-size: 40px;
      box-sizing: border-box;
    }
    .img-ready img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
